package com.ruoyi.web.controller.energy;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.energy.domain.EmsTimeSeriesData;
import com.ruoyi.energy.service.ITDengineTimeSeriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * TDengine时序数据管理Controller
 * 
 * @author ruoyi
 * @date 2025-01-28
 */
@RestController
@RequestMapping("/energy/tdengine")
public class TDengineController extends BaseController {

    @Autowired
    private ITDengineTimeSeriesService tdengineTimeSeriesService;

    /**
     * 初始化TDengine数据库和表结构
     */
    @PreAuthorize("@ss.hasPermi('energy:tdengine:init')")
    @Log(title = "TDengine数据库", businessType = BusinessType.OTHER)
    @PostMapping("/init")
    public AjaxResult initDatabase() {
        try {
            // 创建数据库
            boolean dbResult = tdengineTimeSeriesService.createDatabase("ems_data");
            if (!dbResult) {
                return AjaxResult.error("创建数据库失败");
            }

            // 创建超级表
            boolean stableResult = tdengineTimeSeriesService.createStable("ems_time_series");
            if (!stableResult) {
                return AjaxResult.error("创建超级表失败");
            }

            return AjaxResult.success("TDengine数据库初始化成功");
        } catch (Exception e) {
            logger.error("TDengine数据库初始化失败", e);
            return AjaxResult.error("TDengine数据库初始化失败: " + e.getMessage());
        }
    }

    /**
     * 检查TDengine连接状态
     */
    @GetMapping("/status")
    public AjaxResult checkStatus() {
        try {
            boolean connected = tdengineTimeSeriesService.checkConnection();
            if (connected) {
                return AjaxResult.success("TDengine连接正常");
            } else {
                return AjaxResult.error("TDengine连接失败");
            }
        } catch (Exception e) {
            logger.error("检查TDengine连接失败", e);
            return AjaxResult.error("检查TDengine连接失败: " + e.getMessage());
        }
    }

    /**
     * 插入时序数据
     */
    @PreAuthorize("@ss.hasPermi('energy:tdengine:add')")
    @Log(title = "时序数据", businessType = BusinessType.INSERT)
    @PostMapping("/data")
    public AjaxResult insertData(@RequestBody EmsTimeSeriesData data) {
        try {
            if (data.getTs() == null) {
                data.setTs(new Date());
            }
            boolean result = tdengineTimeSeriesService.insertTimeSeriesData(data);
            return result ? AjaxResult.success("插入成功") : AjaxResult.error("插入失败");
        } catch (Exception e) {
            logger.error("插入时序数据失败", e);
            return AjaxResult.error("插入时序数据失败: " + e.getMessage());
        }
    }

    /**
     * 批量插入时序数据
     */
    @PreAuthorize("@ss.hasPermi('energy:tdengine:add')")
    @Log(title = "时序数据", businessType = BusinessType.INSERT)
    @PostMapping("/data/batch")
    public AjaxResult batchInsertData(@RequestBody List<EmsTimeSeriesData> dataList) {
        try {
            // 设置默认时间戳
            for (EmsTimeSeriesData data : dataList) {
                if (data.getTs() == null) {
                    data.setTs(new Date());
                }
            }
            boolean result = tdengineTimeSeriesService.batchInsertTimeSeriesData(dataList);
            return result ? AjaxResult.success("批量插入成功") : AjaxResult.error("批量插入失败");
        } catch (Exception e) {
            logger.error("批量插入时序数据失败", e);
            return AjaxResult.error("批量插入时序数据失败: " + e.getMessage());
        }
    }

    /**
     * 查询设备最新数据
     */
    @PreAuthorize("@ss.hasPermi('energy:tdengine:query')")
    @GetMapping("/data/latest/{deviceCode}")
    public AjaxResult getLatestData(@PathVariable String deviceCode) {
        try {
            EmsTimeSeriesData data = tdengineTimeSeriesService.selectLatestDataByDevice(deviceCode);
            return AjaxResult.success(data);
        } catch (Exception e) {
            logger.error("查询设备最新数据失败", e);
            return AjaxResult.error("查询设备最新数据失败: " + e.getMessage());
        }
    }
} 